import { getQuery } from 'h3';
import { SiteModel } from '~/server/models/site.model';

// 获取所有站点配置，分页、关键词搜索，使用中的排第一
export default defineEventHandler(async (event): Promise<any> => {
	try {
		const query = getQuery(event);
		const keyword = query.keyword ? String(query.keyword) : '';
		const page = Number(query.page) > 0 ? Number(query.page) : 1;
		const pageSize = Number(query.pageSize) > 0 ? Number(query.pageSize) : 10;

		const filter: any = {};

		if (keyword) {
			filter.$or = [
				{ title: { $regex: keyword, $options: 'i' } },
				{ description: { $regex: keyword, $options: 'i' } },
				{ keywords: { $regex: keyword, $options: 'i' } },
			];
		}

		const total = await SiteModel.countDocuments(filter);

		let list = await SiteModel.find(filter)
			.sort({ isUse: -1, createdAt: -1 })
			.skip((page - 1) * pageSize)
			.limit(pageSize)
			.lean();

		return { code: 1, message: '获取成功', data: { list, total } };
	} catch (error: any) {
		return { code: 0, message: error.message };
	}
});
